package sc.prototype.common.demo;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sc.prototype.common.FileUtil;
import sc.prototype.common.GroovyUtil;
import sc.prototype.common.Utils;

public class GroovyUtilDemo {
    static Logger logger = LoggerFactory.getLogger(GroovyUtilDemo.class);

    public static void parseAndFly(String parsePath) {
        String content = FileUtil.getCPFileAsStringMutely(parsePath);
        Class<Flyable> parseClass = GroovyUtil.parseText(content, Flyable.class);
        logger.info("Class[{}]", parseClass);
        try {
            Flyable flyable = parseClass.newInstance();
            flyable.fly();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 展示如何使用
     */
    @Test
    public void showUse() {
        parseAndFly("sc/prototype/common/demo/MechanicalBird.groovy");
        parseAndFly("sc/prototype/common/demo/MechanicalBirdChanged.groovy");
    }

    /**
     * Class.forName无法使用Groovy编译的类
     */
    @Test
    public void showUse2() {
        String content = FileUtil.getCPFileAsStringMutely("sc/prototype/common/demo/MechanicalBird.groovy");
        Class<Flyable> parseClass = GroovyUtil.parseText(content, Flyable.class);
        logger.info("Class[{}]", parseClass.getName());
        try {
            Class.forName(parseClass.getName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 展示异常情况
     */
    @Test
    public void showError() {
        try {
            parseAndFly("sc/prototype/common/demo/MechanicalBird_error.groovy");
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    /**
     * 编译出的Class是不一样的
     */
    @Test
    public void showClassReparseDiff() {
        String content = FileUtil.getCPFileAsStringMutely("sc/prototype/common/demo/MechanicalBird.groovy");
        Class<Flyable> parseClass1 = GroovyUtil.parseText(content, Flyable.class);
        Class<Flyable> parseClass2 = GroovyUtil.parseText(content, Flyable.class);
        logger.info("Dump1:\r\n" + Utils.toString(parseClass1));
        logger.info("Dump2:\r\n" + Utils.toString(parseClass2));
    }

    /**
     * Groovy每次parseClass都会创建一个类，jvisualvm看JVM的PermGen会暴增，但是当到达一定值时会回收未使用的类
     */
    @Test
    public void showJVMActivity() {
        String content = FileUtil.getCPFileAsStringMutely("sc/prototype/common/demo/MechanicalBird.groovy");
        for (int i = 1; i != 30000; ++i) {
            GroovyUtil.parseText(content, Flyable.class);
            if (i % 1000 == 0) {
                logger.info("已装载{}个类", i);
            }
        }
        logger.info("装载完毕");
        Utils.trySleep(30000);
    }

}
